import {DBManager, Storage} from "mvx-foundation";

/**
 * fix:猜测Taro底层可能进行了URI编码，经测试所有key进行encodeURIComponent有效
 */

class WXStorage implements Storage{
  async get(key: string): Promise<[string, Error | null]> {
    return new Promise(resolve => {
      wx.getStorage({
        key:encodeURIComponent(key),
        success(res) {
          resolve([res.data, null]);
        },
        fail(err) {
          resolve(["", new Error(err.errMsg)]);
        }
      });
    })
  }

  async remove(key: string): Promise<Error | null> {
    return new Promise(resolve => {
      wx.removeStorage({
        key:encodeURIComponent(key),
        success(res) {
          resolve(null);
        },
        fail(err) {
          resolve(new Error(err.errMsg));
        }
      });
    })
  }

  async set(key: string, value: string): Promise<Error | null> {
    return new Promise(resolve => {
      wx.setStorage({
        key:encodeURIComponent(key),
        data:value,
        success(res) {
          resolve(null);
        },
        fail(err) {
          resolve(new Error(err.errMsg));
        }
      });
    })
  }
}

export class WXDBManager extends DBManager {
  protected newSessionStorage():Storage {
    return new WXStorage();
  }

  protected newLocalStorage():Storage {
    return new WXStorage();
  }
}
